<template>
  <div class="admin-boards">
    <div class="page-header">
      <h2>板块管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="openAddBoardDialog">
          <el-icon><Plus /></el-icon> 添加板块
        </el-button>
        <el-button type="info" @click="handleFixArticleCounts">
          <el-icon><RefreshRight /></el-icon> 修复文章数量
        </el-button>
      </div>
    </div>

    <!-- 板块列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>板块列表</span>
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索板块名称"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table
        :data="filteredBoards"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="板块名称" min-width="150" />
        <el-table-column prop="articleCount" label="文章数量" width="100" />
        <el-table-column prop="sort" label="排序值" width="100" sortable />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.state === 0 ? 'success' : 'danger'">
              {{ scope.row.state === 0 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button-group>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon> 编辑
              </el-button>
              <el-button 
                size="small" 
                :type="scope.row.state === 0 ? 'warning' : 'success'"
                @click="handleToggleState(scope.row)"
              >
                <el-icon v-if="scope.row.state === 0"><TurnOff /></el-icon>
                <el-icon v-else><Open /></el-icon>
                {{ scope.row.state === 0 ? '禁用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑板块对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑板块' : '添加板块'"
      width="500px"
    >
      <el-form
        ref="boardFormRef"
        :model="boardForm"
        :rules="boardRules"
        label-width="80px"
      >
        <el-form-item label="板块名称" prop="name">
          <el-input v-model="boardForm.name" placeholder="请输入板块名称" />
        </el-form-item>
        <el-form-item label="排序值" prop="sort">
          <el-input-number v-model="boardForm.sort" :min="0" :max="9999" />
          <div class="form-help-text">数值越小排序越靠前</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitBoard" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Edit, 
  Delete, 
  Search, 
  RefreshRight, 
  TurnOff, 
  Open 
} from '@element-plus/icons-vue'
import api from '@/api'

export default {
  name: 'AdminBoards',
  components: {
    Plus,
    Edit,
    Delete,
    Search,
    RefreshRight,
    TurnOff,
    Open
  },
  setup() {
    // 数据列表
    const loading = ref(false)
    const boards = ref([])
    const searchKeyword = ref('')
    
    // 弹窗相关
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const submitting = ref(false)
    const boardFormRef = ref(null)
    
    // 表单数据
    const boardForm = ref({
      id: null,
      name: '',
      sort: 0
    })
    
    // 表单验证规则
    const boardRules = {
      name: [
        { required: true, message: '请输入板块名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      sort: [
        { required: true, message: '请输入排序值', trigger: 'blur' }
      ]
    }
    
    // 过滤后的板块列表
    const filteredBoards = computed(() => {
      if (!searchKeyword.value) {
        return boards.value
      }
      return boards.value.filter(board => 
        board.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
      )
    })
    
    // 加载板块列表
    const loadBoards = async () => {
      loading.value = true
      try {
        const response = await api.admin.getBoardList()
        console.log('板块列表响应:', response)
        if (response.code === 0) {
          boards.value = response.data || []
          // 对列表按排序值排序
          boards.value.sort((a, b) => a.sort - b.sort)
        } else {
          ElMessage.error(response.message || '获取板块列表失败')
        }
      } catch (error) {
        console.error('获取板块列表出错:', error)
        ElMessage.error('获取板块列表时发生错误')
      } finally {
        loading.value = false
      }
    }
    
    // 打开添加板块对话框
    const openAddBoardDialog = () => {
      isEdit.value = false
      boardForm.value = {
        id: null,
        name: '',
        sort: 0
      }
      dialogVisible.value = true
    }
    
    // 编辑板块
    const handleEdit = (row) => {
      isEdit.value = true
      boardForm.value = {
        id: row.id,
        name: row.name,
        sort: row.sort || 0
      }
      dialogVisible.value = true
    }
    
    // 切换板块状态
    const handleToggleState = async (row) => {
      const newState = row.state === 0 ? 1 : 0
      const actionText = newState === 0 ? '启用' : '禁用'
      
      try {
        const response = await api.admin.setBoardState(row.id, newState)
        if (response.code === 0) {
          ElMessage.success(`${actionText}板块成功`)
          row.state = newState
        } else {
          ElMessage.error(response.message || `${actionText}板块失败`)
        }
      } catch (error) {
        console.error(`${actionText}板块出错:`, error)
        ElMessage.error(`${actionText}板块时发生错误`)
      }
    }
    
    // 删除板块
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除板块 "${row.name}" 吗？删除后无法恢复，且与该板块关联的文章将无法正常显示。`,
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await api.admin.deleteBoard(row.id)
          if (response.code === 0) {
            ElMessage.success('删除板块成功')
            // 从列表中移除
            const index = boards.value.findIndex(item => item.id === row.id)
            if (index !== -1) {
              boards.value.splice(index, 1)
            }
          } else {
            ElMessage.error(response.message || '删除板块失败')
          }
        } catch (error) {
          console.error('删除板块出错:', error)
          ElMessage.error('删除板块时发生错误')
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    // 提交板块表单
    const handleSubmitBoard = async () => {
      if (!boardFormRef.value) return
      
      await boardFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            let response
            if (isEdit.value) {
              // 更新板块
              response = await api.admin.updateBoard(
                boardForm.value.id,
                boardForm.value.name,
                boardForm.value.sort
              )
            } else {
              // 添加板块
              response = await api.admin.addBoard(
                boardForm.value.name,
                boardForm.value.sort
              )
            }
            
            if (response.code === 0) {
              ElMessage.success(isEdit.value ? '更新板块成功' : '添加板块成功')
              dialogVisible.value = false
              loadBoards() // 重新加载列表
            } else {
              ElMessage.error(response.message || (isEdit.value ? '更新板块失败' : '添加板块失败'))
            }
          } catch (error) {
            console.error(isEdit.value ? '更新板块出错:' : '添加板块出错:', error)
            ElMessage.error(isEdit.value ? '更新板块时发生错误' : '添加板块时发生错误')
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    // 搜索处理
    const handleSearch = () => {
      // 使用计算属性自动过滤
    }
    
    // 修复文章数量
    const handleFixArticleCounts = async () => {
      try {
        ElMessage.info('正在修复板块文章数量，请稍候...')
        const response = await api.admin.fixBoardArticleCounts()
        if (response.code === 0) {
          const { totalChecked, totalFixed } = response.data
          ElMessage.success(`修复完成! 共检查 ${totalChecked} 个板块，修复 ${totalFixed} 个板块。`)
          loadBoards() // 重新加载列表
        } else {
          ElMessage.error(response.message || '修复板块文章数量失败')
        }
      } catch (error) {
        console.error('修复板块文章数量出错:', error)
        ElMessage.error('修复板块文章数量时发生错误')
      }
    }
    
    // 初始化
    onMounted(() => {
      loadBoards()
    })
    
    return {
      loading,
      boards,
      filteredBoards,
      searchKeyword,
      dialogVisible,
      isEdit,
      submitting,
      boardForm,
      boardRules,
      boardFormRef,
      loadBoards,
      openAddBoardDialog,
      handleEdit,
      handleToggleState,
      handleDelete,
      handleSubmitBoard,
      handleSearch,
      handleFixArticleCounts
    }
  }
}
</script>

<style scoped>
.admin-boards {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  width: 250px;
}

.form-help-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.el-button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-box {
    width: 100%;
  }
}
</style> 